package com.junki.officecontentsearch.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.junki.officecontentsearch.entity.IndexFile;
import com.junki.officecontentsearch.repository.IndexFileRepository;
import com.junki.officecontentsearch.service.IndexFileService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author junki
 * @date 2021/5/28 15:18
 */
@Service
public class IndexFileServiceImpl implements IndexFileService {

    @Resource
    private IndexFileRepository indexFileRepository;

    @Resource
    private ElasticsearchRestTemplate esRestTemplate;

    @Override
    public IndexFile add(IndexFile indexFile) {
        return indexFileRepository.save(indexFile);
    }

    @Override
    public List<IndexFile> findByContentKeyword(String keyword, Boolean matchQuery) {
        // 对content进行分词匹配
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 是否匹配查询
        if (matchQuery) {
            // 匹配查询，关键字会被分词
            boolQueryBuilder.must(QueryBuilders.matchQuery("content", keyword));
        } else {
            // 词项查询，关键字不会被分词
            boolQueryBuilder.must(QueryBuilders.termQuery("content", keyword));
        }

        // 对content进行高亮处理，高亮文字加上<mark></mark>标签
        HighlightBuilder highlightBuilder = new HighlightBuilder()
                .field("content")
                .preTags("<mark>")
                .postTags("</mark>");

        // 构建本地查询
        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQueryBuilder)
                .withHighlightBuilder(highlightBuilder)
                .build();

        // 查询结果
        SearchHits<IndexFile> searchHits = esRestTemplate.search(nativeSearchQuery, IndexFile.class);

        // 处理结果，将原content替换为高亮结果
        return searchHits.stream().map(searchHit -> {
            IndexFile indexFile = searchHit.getContent();
            indexFile.setContentResult(CollectionUtil.join(searchHit.getHighlightField("content"), ""));
            indexFile.setScore(searchHit.getScore());
            return indexFile;
        }).collect(Collectors.toList());
    }

}
